package edu.zsl.controller;

import edu.zsl.pojo.Score;
import edu.zsl.service.ScoreService;
import jakarta.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class ScoreController {
    private final ScoreService scoreService;

    @Autowired
    public ScoreController(ScoreService scoreService) {
        this.scoreService = scoreService;
    }
    // 加载页面
    @GetMapping("/scorepage")
    public String getScorePage() {
        return "score";
    }

    //根据学号查询成绩并带上学生名称和课程名称
    @GetMapping("/searchScores")
    public String searchScoreWithName(@RequestParam("id") String studentId, Model model) {
        List<Score> scores = scoreService.searchScoreWithName(studentId);
        //显示学生所有课程成绩的平均分 注意！！！应该使用double类型而不是score
        Double scoreAvg = scoreService.getAvgScore(studentId);
        model.addAttribute("scores", scores);
        model.addAttribute("scoreAvg", scoreAvg);
        // 学生成绩记录总条数
        int totalCount = scores.size();
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("showAverageColumn", true);// 显示平均分列
        return "score";//注意！！！这里应该于score.html文件名一致
    }
    //查询全部人的成绩
    @GetMapping("/scores")
    public String searchAllScores(Model model) {
        List<Score> scores = scoreService.getAllScores();
        model.addAttribute("scores", scores);
        model.addAttribute("showAverageColumn", false);// 不显示平均分列
        return "score";
    }
    //添加学生成绩
    @GetMapping("/addscorepage")
    public String addScorePage() {
        return "addscore";
    }
    //新增的成绩保存到数据库，并重定向到scores页面
    @PostMapping("/addscore")
    public String addScore(Score score) {
        scoreService.addScore(score);
        return "redirect:/scores";
    }
    //删除学生成绩
    @GetMapping("/deletescore/{id}")
    public String deleteScore(@PathVariable Integer id,Model model) {
        scoreService.deleteScore(id);
        return "redirect:/scores";
    }
    //修改学生成绩页面
    @GetMapping("/updatescorepage/{id}")
    public String updateScorePage(@PathVariable Integer id,Model model) {
        Score score = scoreService.getScoreById(id);
        model.addAttribute("score", score);
        return "updatescore";
    }
    //将更新后的表单数据保存到数据库，重定向到scores页面
    @PostMapping("/updatescore")
    public String updateScore(@ModelAttribute Score score) {
        scoreService.updateScore(score);
        return "redirect:/scores";
    }
}
